package com.ysd.lis.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysBasDict;
import com.ysd.lis.entity.WkCalcCommon;
import com.ysd.lis.entity.WkCalcCommonDetail;
import com.ysd.lis.mapper.WkCalcCommonDetailMapper;
import com.ysd.lis.request.WkCalcCommonDetailRequest;
import com.ysd.lis.service.WkCalcCommonDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;

/**
 * 绩效考核-公共参数（属性值配置）
 *
 * @author LuoXS
 * @date 2024/4/16
 * version 1.0
 */
@Service
@Slf4j
public class WkCalcCommonDetailServiceImpl extends ServiceImpl<WkCalcCommonDetailMapper, WkCalcCommonDetail> implements WkCalcCommonDetailService {

    @Resource
    WkCalcCommonDetailMapper mapper;


    @Override
    public Result pageList(WkCalcCommonDetailRequest.PageParam pageParam) {
        Result result;
        try {
            MPJLambdaWrapper<WkCalcCommonDetail> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.selectAll(WkCalcCommonDetail.class)
                    .selectAs("b", WkCalcCommon::getIsEdit, WkCalcCommonDetail::getIsParentEdit)
                    .leftJoin(WkCalcCommon.class, "a", WkCalcCommon::getId, WkCalcCommonDetail::getPid)
                    .leftJoin(WkCalcCommon.class, "b", WkCalcCommon::getId, WkCalcCommon::getPid);

            queryWrapper.eq(WkCalcCommon::getPid, pageParam.getPid());

            queryWrapper.eq(WkCalcCommonDetail::getDelFlag, 0)
                    .orderByAsc(WkCalcCommonDetail::getSx);

            List<Map<String, Object>> list = new ArrayList<>();
            List<WkCalcCommonDetail> dictList = mapper.selectList(queryWrapper);


            Map<String, List<WkCalcCommonDetail>> collect = dictList.stream().collect(Collectors.groupingBy(WkCalcCommonDetail::getCommonId));
            Set<String> commonIds = collect.keySet();
            for (String commonId : commonIds) {
                List<WkCalcCommonDetail> dicts = collect.get(commonId);
                Map<String, Object> map = new HashMap<>();
                map.put("commonId", commonId);
                for (WkCalcCommonDetail dictitem : dicts) {
                    map.put(dictitem.getCode(), dictitem.getValue());
                    map.put("sx", dictitem.getSx());
                    map.put("isParentEdit", dictitem.getIsParentEdit());
                    map.put("grade", dictitem.getGrade());
                }
                list.add(map);
            }
            List<Map<String, Object>> no = list.stream().sorted(comparing(l -> (Integer) l.get("sx"))).collect(Collectors.toList());

            result = Result.succ(no);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail(400, "查询失败！", e.getMessage());
        }
        return result;
    }

    @Override
    public Result option(WkCalcCommonDetailRequest.OptionParams params) {
        Result result = Result.succ(1, "添加成功！", null);
        try {
            List<WkCalcCommonDetail> addList = params.getAddList();
            List<WkCalcCommonDetail> updateList = params.getUpdateList();
            if (CollectionUtil.isNotEmpty(addList)) {
                Map<Integer, List<WkCalcCommonDetail>> collect = addList.stream().collect(Collectors.groupingBy(WkCalcCommonDetail::getSx));
                for (Map.Entry<Integer, List<WkCalcCommonDetail>> integerListEntry : collect.entrySet()) {
                    List<WkCalcCommonDetail> list = integerListEntry.getValue();
                    String commonId = IdUtil.getSnowflake().nextId() + "";
                    for (WkCalcCommonDetail detail : list) {
                        detail.setCommonId(commonId);
                    }
                    this.saveBatch(list);
                }
            }

            if (CollectionUtil.isNotEmpty(updateList)) {
                for (WkCalcCommonDetail detail : updateList) {
                    String commonId = detail.getCommonId();
                    String pid = detail.getPid();
                    LambdaQueryWrapper<WkCalcCommonDetail> eq = new LambdaQueryWrapper<WkCalcCommonDetail>()
                            .eq(WkCalcCommonDetail::getCommonId, commonId)
                            .eq(WkCalcCommonDetail::getPid, pid);
                    mapper.update(detail, eq);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail(400, "添加失败！", e.getMessage());
        }
        return result;
    }

    @Override
    public Result delete(WkCalcCommonDetail entity) {
        Result result;
        try {
            LambdaQueryWrapper<WkCalcCommonDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WkCalcCommonDetail::getCommonId, entity.getCommonId());
            int delete = mapper.delete(wrapper);
            if (delete > 0) {
                result = Result.succ(1, "删除成功", null);
            } else {
                result = Result.fail(400, "删除失败", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail(400, "删除失败", e.getMessage());
        }
        return result;
    }
}
